package com.lzx.adx.report.controller.v1.hw;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lzs.adx.commmon.utils.JsonUtils;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.bean.mapper.ReportMapper;
import com.lzx.adx.report.cache.AccountLocalCache;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.enums.HhHwEnum;
import com.lzx.adx.report.enums.XhsCovetHwEventTypeEnums;
import com.lzx.adx.report.model.huawei.request.HwReportRequest;
import com.lzx.adx.report.model.huawei.request.HwUploadRequest;
import com.lzx.adx.report.service.ReportService;
import com.lzx.adx.report.util.HwSecureUtil;
import com.lzx.adx.report.util.UrlUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/hw/yy")
@RestController
@Slf4j
public class HwYYReportController {


    @Autowired
    private ReportService reportService;


    @Autowired
    private ThreadPoolTaskExecutor reportExecutor;

    @Autowired
    private ReportMapper reportMapper;


    @GetMapping("/report")
    public ResponseEntity hwReqport(HwReportRequest hwReportRequest, HttpServletRequest request) {
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(hwReportRequest.getDspId());
        log.info("收到华为到{}的参数为{}", accountDTO.getName(),JSON.toJSONString(hwReportRequest));
        if (StringUtils.isNotBlank(hwReportRequest.getTransunique_id())) {
            hwReportRequest.setRequestId(hwReportRequest.getTransunique_id());
        }
        //1.收到监测的数据存储
        ReportDTO reportDTO = reportMapper.toReportDTO(hwReportRequest);
        reportDTO.setEventType(hwReportRequest.getType());
        reportDTO.setBizRequestId(IdUtil.fastUUID());
        reportDTO.setCreateTime(new Date());
        reportDTO.setUpdateTime(new Date());
        reportDTO.setExtend(JSON.toJSONString(hwReportRequest));
        reportExecutor.execute(() -> {
            reportService.saveData(reportDTO);
        });
        //获取配置信息
        //3.处理参数和URL
        String resultUrl = UrlUtil.covertHHUrl(accountDTO, reportDTO);
        log.info("账户号为{}，完整的华为到YY(辉煌明天)请求地址为{}", hwReportRequest.getDspId(), resultUrl);
        //2.2调用饿了嘛，上报接口
        String body = HttpUtil.createGet(resultUrl).execute().body();
        log.info("账户号为{}，完整的华为到YY(辉煌明天)，响应的结果为{}", hwReportRequest.getDspId(), body);
        return ResponseEntity.ok(new Result());
    }


    @GetMapping("callback")
    public ResponseEntity callBackUrl(String requestId, String event_type) throws Exception {
        log.info("华为收到了YY(辉煌明天)回调信息请求流水号{},回调类型为{}", requestId, event_type);
        if (StringUtils.isBlank(requestId)) {
            log.error("华为收到了YY(辉煌明天)回调信息流水号空");
            return ResponseEntity.ok(new Result());
        }
        if (StringUtils.isBlank(event_type)) {
            log.info("请求流水号{},华为收到了YY(辉煌明天)回调信息，回调类型为空，不做回传", requestId);
            return ResponseEntity.ok(new Result());
        }
        String hwCode = HhHwEnum.getHwCode(event_type);
        if (null == hwCode) {
            log.info("请求流水号{},华为收到了YY回调信息，回调类型异常，不做回传", requestId);
            return ResponseEntity.ok(new Result());
        }
        if ("activate".equals(hwCode)) {
            log.info("请求流水号{},华为收到了YY回调信息，回调类型异常，不做回传", requestId);
            return ResponseEntity.ok(new Result());
        }
        //1.把转换结果更新到数据库
        long currentTimeMillis = System.currentTimeMillis();
        Map<String, Object> params = new HashMap<>();
        params.put("bizRequestId", requestId);
        List<ReportDTO> list = reportService.list(params);
        ReportDTO reportDTO;
        if (CollectionUtil.isNotEmpty(list)) {
            reportDTO = list.get(0);
            reportDTO.setResultType(event_type);
            reportDTO.setResultTime(String.valueOf(currentTimeMillis));
            reportDTO.setUpdateTime(new Date());
            reportService.updateData(reportDTO,event_type);
        } else {
            log.error("当前流水号，系统当前不存在");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        //2.从缓存加载配置
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(reportDTO.getDspId());
        //2.回调渠道，调用华为回传接口
        HwUploadRequest hwUploadRequest = new HwUploadRequest();
        hwUploadRequest.setOaid(reportDTO.getOaid());
        hwUploadRequest.setConversion_type(hwCode);
        hwUploadRequest.setTimestamp(String.valueOf(currentTimeMillis));
        hwUploadRequest.setCallback(reportDTO.getCallback());
        hwUploadRequest.setCampaign_id(reportDTO.getCampaignId());
        hwUploadRequest.setContent_id(reportDTO.getContentId());
        hwUploadRequest.setConversion_time(String.valueOf(currentTimeMillis / 1000));
        hwUploadRequest.setTracking_enabled("1");
        if (hwCode.equals("paid")) {
            HwUploadRequest.ConversionExtend extendMap = new HwUploadRequest.ConversionExtend();
            hwUploadRequest.setConversion_extend(extendMap);
        }
        String paramsBody = JsonUtils.toJsonString(hwUploadRequest);
        log.info("账号为{}请求流水号{}YY(辉煌明天)给华为请求的参数为{}", reportDTO.getDspId(), requestId, paramsBody);
        Map<String, String> header = new HashMap<>();
        header.put("Authorization", HwSecureUtil.buildAuthorizationHeader(paramsBody, accountDTO.getSspKey()));
        HttpRequest body = HttpUtil.createPost(accountDTO.getSspApiUrl()).addHeaders(header).body(paramsBody);
        String result = body.execute().body();
        log.info("账号为{}请求流水号{}YY(辉煌明天)给华为转换响应的结果为{}", reportDTO.getDspId(), requestId, result);
        return ResponseEntity.ok(new Result());
    }









    @GetMapping("/yt/callback")
    public ResponseEntity ytCallBackUrl(String requestId, String event_type) throws Exception {
        log.info("华为收到了一淘(辉煌明天)回调信息请求流水号{},回调类型为{}", requestId, event_type);
        if (StringUtils.isBlank(requestId)) {
            log.error("华为收到了一淘(辉煌明天)回调信息流水号空");
            return ResponseEntity.ok(new Result());
        }
        if (StringUtils.isBlank(event_type)) {
            log.info("请求流水号{},华为收到了一淘(辉煌明天)回调信息，回调类型为空，不做回传", requestId);
            return ResponseEntity.ok(new Result());
        }
        String hwCode = HhHwEnum.getHwCode(event_type);
        if (null == hwCode) {
            log.info("请求流水号{},华为收到了一淘(辉煌明天)回调信息，回调类型异常，不做回传", requestId);
            return ResponseEntity.ok(new Result());
        }
        if ("register".equals(hwCode)||"retain".equals(hwCode)){
            log.info("请求流水号{},华为收到了一淘(辉煌明天)回调信息，回调类型异常，不做回传", requestId);
            return ResponseEntity.ok(new Result());
        }
        //1.把转换结果更新到数据库
        long currentTimeMillis = System.currentTimeMillis();
        Map<String, Object> params = new HashMap<>();
        params.put("bizRequestId", requestId);
        List<ReportDTO> list = reportService.list(params);
        ReportDTO reportDTO;
        if (CollectionUtil.isNotEmpty(list)) {
            reportDTO = list.get(0);
            reportDTO.setResultType(event_type);
            reportDTO.setResultTime(String.valueOf(currentTimeMillis));
            reportDTO.setUpdateTime(new Date());
            reportService.updateData(reportDTO,event_type);
        } else {
            log.error("当前流水号，系统当前不存在");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        //2.从缓存加载配置
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(reportDTO.getDspId());
        //2.回调渠道，调用华为回传接口
        HwUploadRequest hwUploadRequest = new HwUploadRequest();
        hwUploadRequest.setOaid(reportDTO.getOaid());
        hwUploadRequest.setConversion_type(hwCode);
        hwUploadRequest.setTimestamp(String.valueOf(currentTimeMillis));
        hwUploadRequest.setCallback(reportDTO.getCallback());
        hwUploadRequest.setCampaign_id(reportDTO.getCampaignId());
        hwUploadRequest.setContent_id(reportDTO.getContentId());
        hwUploadRequest.setConversion_time(String.valueOf(currentTimeMillis / 1000));
        hwUploadRequest.setTracking_enabled("1");
        if (hwCode.equals("paid")) {
            HwUploadRequest.ConversionExtend extendMap = new HwUploadRequest.ConversionExtend();
            hwUploadRequest.setConversion_extend(extendMap);
        }
        String paramsBody = JsonUtils.toJsonString(hwUploadRequest);
        log.info("账号为{}请求流水号{}一淘(辉煌明天)给华为请求的参数为{}", reportDTO.getDspId(), requestId, paramsBody);
        Map<String, String> header = new HashMap<>();
        header.put("Authorization", HwSecureUtil.buildAuthorizationHeader(paramsBody, accountDTO.getSspKey()));
        HttpRequest body = HttpUtil.createPost(accountDTO.getSspApiUrl()).addHeaders(header).body(paramsBody);
        String result = body.execute().body();
        log.info("账号为{}请求流水号{}一淘(辉煌明天)给华为转换响应的结果为{}", reportDTO.getDspId(), requestId, result);
        return ResponseEntity.ok(new Result());
    }







}
